<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:15%;padding: 0">
      <TableClassify
        :title="classifyTitle"
        :treeData="classifyData"
        @select="masterRowClick"
        :replaceFields="{ title: 'classifyName', key: 'uuid' }"
        :loading="masterConfirmLoading"
        searchPlaceholder="名称"
        searchFieldName="classifyName"
      ></TableClassify>
    </div>
    <div class="page-common-content">
      <tool-bar @search="$refs.subList.refresh(true)" @reset="resetSearchForm">
        <template slot="toolBtn" slot-scope="scope">
          <a-button
            class="cu-btn-primary"
            icon="plus"
            @click="
              openCardSelection(
                'add',
                $ct('SelectCreateFormType', '选择创建表单类型')
              )
            "
            >{{ $ct("CreateNewForm", "创建新表单") }}</a-button
          >
          <a-button icon="upload" @click="importReportFile" type="link">{{
            $ct("Import", "导入")
          }}</a-button>
          <!-- <a-button
							icon="edit"
							@click="cardReportVisible = true"
              type="link"
					>{{$ct("reportTypeToCreate","新建报表")}}</a-button> -->
        </template>
        <template slot="toolForm">
          <a-form-item :label="$ct('FormName', '表单名称')">
            <a-input
              v-model="subQueryParam.name"
              :placeholder="$ct('FormName', '表单名称')"
            />
          </a-form-item>
        </template>
      </tool-bar>
      <DataGrid
        ref="subList"
        type="sub"
        :url="url"
        :columns="subColumns"
        :queryParam="subQueryParam"
        rowKey="uuid"
        showPagination="auto"
        :showRowSelect="false"
      >
        <span slot="renderType" slot-scope="{ text, record }">
          {{ text | typeStr }}
        </span>
        <span slot="renderStatus" slot-scope="{ text, record }">
          <a-switch
            size="small"
            :checked="text == 'true' ? true : false"
            @change="(e) => stateChange(e, record)"
          />
        </span>
        <span slot="renderFormVersion" slot-scope="{ text, record }">
          <a-tag v-if="record.version" :color="'geekblue'">
            {{ "V:" + record.version }}
          </a-tag>
        </span>
        <span slot="renderAction" slot-scope="{ text, record }">
          <template>
            <a @click="handleViewDesign(record)">{{ $ct("design", "设计") }}</a>
            <span class="action-margin"></span>
            <a @click="handleDelSub(record)" class="action-delete">{{
              $ct("delete", "删除")
            }}</a>
            <span class="action-margin"></span>
            <a-dropdown>
              <a class="ant-dropdown-link">
                {{ $ct("more", "更多") }}
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a
                    @click="
                      openCardSelection(
                        'preview',
                        $ct('FormPreview', '表单预览'),
                        record
                      )
                    "
                    >{{ $ct("previewForm", "预览表单") }}</a
                  >
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleCopyForm(record)">
                    {{ $ct("copyForm", "复制表单") }}</a
                  >
                </a-menu-item>
                <a-menu-item v-if="record.status == 'true'">
                  <a @click="handleRelease(record)">
                    {{ $ct("bindMenu", "绑定菜单") }}</a
                  >
                </a-menu-item>
                <!-- <a-menu-item >
                  <a @click="handleReport(record)"> {{$ct("bindReport","绑定报表")}}</a>
                </a-menu-item> -->
                <a-menu-item>
                  <a
                    @click="
                      openCardSelection(
                        'downloadCode',
                        $ct('downloadCode', '下载代码'),
                        record
                      )
                    "
                    >{{ $ct("downloadCode", "下载代码") }}</a
                  >
                </a-menu-item>
                <a-menu-item>
                  <a @click="exportJSON(record)">{{
                    $ct("exportData", "导出数据")
                  }}</a>
                </a-menu-item>
                <a-menu-item v-if="record.type === 'normalForm'">
                  <a @click="handleAdjustLayout(record)">{{
                    $ct("adjustLayout", "调整布局")
                  }}</a>
                </a-menu-item>
                <!-- 					<a-menu-item>
								  <a @click="handleRelease(record)">版本管理</a>
								</a-menu-item> -->
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </DataGrid>
      <edit-form
        :visible="subVisible"
        :loading="subConfirmLoading"
        :model="subMdl"
        @cancel="handleCancel('sub')"
        @ok="handleOk('sub')"
      />
      <card-selection
        ref="cardModal"
        :visible="cardVisible"
        :type="cardType"
        @click="openPage"
        @cancel="() => (cardVisible = false)"
      />
      <card-selection-report
        ref="subModal"
        :visible="cardReportVisible"
        type="add"
        @click="openPage"
        @cancel="() => (cardReportVisible = false)"
        title="选择创建报表类型"
        :width="470"
      />
      <design-form
        ref="designModal"
        :key="designTimeString"
        @cancel="handleCancelDesign()"
        @ok="handleOkDesign()"
        :formType="formType"
        :visibleDesign="visibleDesign"
        :isEdit="isEdit"
      />
      <template-form
        ref="templateForm"
        :key="templateTimeString"
        :visible="templateVisible"
        @handleViewDesign="handleViewDesign"
        @cancel="handleCancelTemplate"
      />
      <template-form-report
        ref="templateFormReport"
        :key="'3'"
        :visible.sync="templateReportVisible"
      />
      <!-- 发布菜单 -->
      <release-modal
        ref="releaseModal"
        @ok="handleReleaseOk()"
        :visible.sync="visibleRelease"
        :loading="releaseConfirmLoading"
        :model="releaseMdl"
      ></release-modal>
      <report-modal
        ref="reportModal"
        @ok="handleReportOk"
        :visible.sync="visibleReport"
        :mdl="releaseMdl"
        @update:visible="
          (flag) => {
            visibleReport = flag;
          }
        "
      ></report-modal>
      <app-form-preview
        :visible.sync="h5PreviewVisible"
        :src="h5PreviewSrc"
      ></app-form-preview>
      <a-modal
        title="扫码预览"
        :visible="qrVisible"
        :width="330"
        :footer="null"
        @cancel="(e) => (qrVisible = false)"
      >
        <vue-qr :text="qrValue" :size="300" :correctLevel="3"></vue-qr>
        <div class="text-center text-xs padding-xs">使用app扫码预览</div>
      </a-modal>
      <!-- 导入文件 -->
      <web-upload
        ref="webUploadModal"
        :visible="visibleFile"
        :showTipText="true"
        :width="450"
        url="/form/formBasicConfigure/importFormJson"
        @cancel="() => (visibleFile = false)"
        @ok="importReportJson"
      />
      <!-- 修改布局 -->
      <adjustLayout
        ref="adjustLayoutModal"
        :visible="layoutVisible"
        :width="500"
        :uuid="layoutUuid"
        @handleAdd="handleAddLayout"
        @close="() => (layoutVisible = false)"
      />
      <designLayout
        ref="designModalLayout"
        @cancel="() => (visibleDesignLayout = false)"
        @ok="() => (visibleDesignLayout = false)"
        :formType="formType"
        :visibleDesign="visibleDesignLayout"
        :isEdit="isEdit"
      />
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { baseUrl } from "@/services/baseUrl.js";
import { h5PreviewUrl } from "@/services/baseUrl";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { TreeGrid, DataGrid, TableClassify } from "@/components";
import { treeGridMixin } from "@/mixins/treeGridMixin";
import editForm from "./edit.vue";
import cardSelection from "./cardSelection.vue";
import KFormPreview from "@/components/TopVUI/k-form-design/packages/KFormPreview/index";
import designForm from "./design.vue";
import templateForm from "./templates.vue";
import releaseModal from "./releaseModal.vue";
import reportModal from "./reportModal.vue";
import appFormPreview from "./appFormPreview.vue";
import vueQr from "vue-qr";
import { getToken } from "@/utils/TopVUI";
import adjustLayout from "./adjustLayout.vue";
import designLayout from "./designLayout.vue";
import cardSelectionReport from "@/pages/report/templet/cardSelection.vue";
import templateFormReport from "@/pages/report/templet/templates.vue";
export default {
  mixins: [treeGridMixin],
  components: {
    TreeGrid,
    editForm,
    cardSelection,
    DataGrid,
    KFormPreview,
    designForm,
    templateForm,
    releaseModal,
    appFormPreview,
    vueQr,
    TableClassify,
    adjustLayout,
    designLayout,
    cardSelectionReport,
    templateFormReport,
    reportModal,
  },
  provide() {
    // 使用函数的形式，可以访问到 `this`
    return {
      sameValue: false,
    };
  },
  filters: {
    typeStr(val) {
      switch (val) {
        case "normalForm":
          return "普通表单";
        case "flowForm":
          return "流程表单";
        case "createPage":
          return "页面设计";
        case "viewData":
          return "视图数据";
        case "treeForm":
          return "树形表单";
      }
    },
  },
  data() {
    return {
      designTimeString: "1",
      templateTimeString: "2",
      key: "1",
      columns: [
        {
          title: "分类名称",
          dataIndex: "text",
          langCode: "classificationName",
          ellipsis: true,
        },
      ],
      subColumns: [
        {
          title: "名称",
          dataIndex: "name",
          width: 180,
          fixed: "left",
        },
        {
          title: "编码",
          dataIndex: "code",
          width: 200,
        },
        {
          title: "类型",
          align: "center",
          dataIndex: "type",
          width: 100,
          scopedSlots: {
            customRender: "renderType",
          },
        },
        {
          title: "web菜单",
          align: "center",
          dataIndex: "webMenuName",
          width: 100,
        },
        {
          title: "app菜单",
          align: "center",
          dataIndex: "appMenuName",
          width: 100,
        },
        {
          title: "表单ID",
          align: "center",
          dataIndex: "uuid",
          width: 300,
        },
        {
          title: "状态",
          align: "center",
          dataIndex: "status",
          langCode: "state",
          width: 80,
          scopedSlots: {
            customRender: "renderStatus",
          },
        },
        {
          title: "排序",
          width: 40,
          align: "center",
          dataIndex: "sort",
          sorter: true,
        },
        {
          title: "操作",
          align: "center",
          dataIndex: "action",
          width: 180,
          scopedSlots: {
            customRender: "renderAction",
          },
          fixed: "right",
        },
      ],
      masterVisible: false,
      subVisible: false,
      masterConfirmLoading: false,
      subConfirmLoading: false,
      visibleVersion: false,
      confirmLoadingVersion: false,
      mdlVersion: null,
      masterMdl: null,
      subMdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      subQueryParam: {},
      url: {
        masterList: "/form/formModule/selectAll",
        subList: "/form/formBasicConfigure/getPageSet",
        subSave: "/form/formTable/save",
        subUpdate: "/form/formTable/update",
        subDelete: "/form/formBasicConfigure/deleteBatch",
        importExcelUrl: "/form/formBasicConfigure/importFormJson",
      },
      parameter: {
        father: {
          levelId: 1,
        },
        children: {},
      },
      visibleDesign: false,
      visibleRelease: false,
      releaseConfirmLoading: false,
      releaseMdl: {},
      cardVisible: false,
      cardType: "",
      templateVisible: false,
      formType: "",
      isEdit: false,
      previewMdl: null,
      h5PreviewVisible: false,
      h5PreviewSrc: "",
      qrVisible: false,
      qrValue: "",
      visibleFile: false,
      classifyData: [],
      classifyTitle: "表单分类",
      masterListKey: "",
      layoutVisible: false,
      layoutUuid: null,
      layoutData: {},
      visibleDesignLayout: false,
      cardReportVisible: false, //新增新建报表card
      templateReportVisible: false, //新增新建报表模板方式
      visibleReport: false,
    };
  },
  activated() {},
  mounted() {
    this.getClassifyData();
  },
  methods: {
    masterRowClick(e) {
      this.subQueryParam.puuid = e[0];
      this.masterListKey = e[0];
      this.$refs.subList.rows = null;
      this.$refs.subList.refresh();
    },
    //获取分类数据
    getClassifyData() {
      this.masterConfirmLoading = true;
      this.$post(this.url.masterList).then((res) => {
        if (res.statusCode === 200) {
          this.classifyData = res.data;
          this.masterConfirmLoading = false;
        } else {
          this.$message.error(res.message ? res.message : "请求数据失败");
          this.masterConfirmLoading = false;
        }
      });
    },
    // 新增
    openCardSelection(type, title = "表单预览", record) {
      if (record?.type === "createPage" && type === "preview") {
        this.$router.push({
          path: "/form/pageDesign/pageView?tableUuid=" + record.uuid,
        });
      } else {
        this.cardType = type;
        this.cardVisible = true;
        this.previewMdl = record;
      }
      this.$refs.cardModal.title = title;
    },
    // 打开设计页面
    openPage(key) {
      let token = Vue.ls.get(ACCESS_TOKEN);
      // this.$refs.designModal.getData(null, this.subMdl);
      if (key === "treeForm") {
        this.visibleDesign = true;
      } else if (key === "normalForm") {
        this.visibleDesign = true;
      } else if (key === "flowForm") {
        this.visibleDesign = true;
        this.$nextTick(() => {
          this.$refs.designModal.stepList.push({
            name: "流程设计",
            key: 5,
          });
          this.$refs.designModal.leftStep.padding = "0 6%";
        });
      } else if (key === "viewData") {
        this.visibleDesign = true;
        this.$refs.designModal.stepList.splice(1, 2);
      } else if (key === "createPage") {
        this.visibleDesign = true;
        this.$refs.designModal.stepList.splice(3, 1);
      } else if (key === "webPreview") {
        this.webPreviewForm();
      } else if (key === "h5Preview") {
        this.h5PreviewSrc =
          h5PreviewUrl +
          "/#/pages/model/list/list?uuid=" +
          this.previewMdl.uuid +
          "&token=" +
          Vue.ls.get(ACCESS_TOKEN);
        this.h5PreviewVisible = true;
      } else if (key === "appPreview") {
        this.qrVisible = true;
        this.qrValue = this.previewMdl.uuid;
      } else if (key === "downloadWebCode") {
        window.location.href =
          baseUrl +
          "/form/formGen/generateCode?type=web&uuid=" +
          this.previewMdl.uuid +
          "&token=" +
          Vue.ls.get(ACCESS_TOKEN);
      } else if (key === "downloadAppCode") {
        window.location.href =
          baseUrl +
          "/form/formGen/generateCode?type=app&uuid=" +
          this.previewMdl.uuid +
          "&token=" +
          Vue.ls.get(ACCESS_TOKEN);
      } else if ("normalReport" === key) {
        window.open(
          baseUrl + "/report/ureport/designer?token=" + token,
          "_blank"
        );
      } else if ("createTemplate" === key) {
        this.$refs.templateFormReport.getAllListData();
        this.templateReportVisible = true;
      }
      this.cardVisible = false;
      this.cardReportVisible = false;
      this.formType = key;
      this.isEdit = false;
    },
    handleCancelTemplate() {
      this.templateTimeString = Date.now().valueOf();
      this.templateVisible = false;
    },
    // 设计
    handleViewDesign(e) {
      if (e.type === "createPage") {
        this.$refs.designModal.stepList.splice(3, 1);
      } else if (e.type === "viewData") {
        this.$refs.designModal.stepList.splice(1, 2);
      }
      this.formType = e.type;
      this.$refs.designModal.getData(e);
      this.visibleDesign = true;
      this.isEdit = true;
    },
    handleOkDesign() {
      this.$refs.subList.refresh();
      this.visibleDesign = false;
      this.designTimeString = Date.now().valueOf();
      // this.$refs.subList.selectedRowKeys = [];
      // this.$refs.subList.selectedRows = [];
    },
    // web端预览表单
    webPreviewForm() {
      let MIS_ACCESS_TOKEN = localStorage.getItem("MIS_ACCESS_TOKEN");
      if (MIS_ACCESS_TOKEN) {
        // topjui版
        this.$router.push({
          path:
            "/form/formDefine/viewTopjui?tableName=" +
            this.previewMdl.tableName,
        });
      } else {
        this.$router.push({
          path: "/form/formDefine/view?tableUuid=" + this.previewMdl.uuid,
        });
      }
    },
    // 预览
    handlePreview(val) {
      if (!val.fieldJson) {
        return this.$message.warn("请先设计表单！", 2);
      }
      this.$refs.previewModal.jsonData = JSON.parse(val.fieldJson);
      // this.$refs.previewModal.previewWidth = this.previewOptions.width;
      this.$refs.previewModal.visible = true;
    },
    handleCancelDesign(e) {
      this.visibleDesign = false;
      this.designTimeString = Date.now().valueOf();
    },
    handleDelSub(record, type) {
      let that = this;
      that.$confirm({
        title: that.$ct("tips", "提示"),
        content: () =>
          that.$createElement("span", [
            "确定删除该数据吗？删除之后不可恢复！",
            this.$createElement("br"),
            "删除后绑定的菜单也将一并删除，请手动刷新浏览器！",
          ]),
        okText: that.$ct("confirm", "确定"),
        cancelText: that.$ct("cancel", "取消"),
        closable: true,
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that
            .$post(that.url.subDelete, {
              uuid: record.uuid,
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success(
                  "删除成功，如果绑定了菜单请刷新页面",
                  1.5
                );
                that.$refs.subList.refresh();
              } else {
                that.$message.error(res.message);
              }
            });
        },
      });
    },
    // 发布菜单
    handleRelease(record) {
      let text = "";
      // if(record.webMenuUuid){
      //   text += "此表单已绑定在web端【" + record.webMenuName + "】菜单下"
      // }
      // if(record.appMenuUuid){
      //   text = text?text+"，":text
      //   text += "此表单已绑定在app端【" + record.appMenuName + "】菜单下"
      // }
      if (record.webMenuUuid && record.appMenuUuid) {
        return this.$message.info(
          "此表单已绑定：web端【" +
            record.webMenuName +
            "】，app端【" +
            record.appMenuName +
            "】",
          1.5
        );
      }
      const form = this.$refs.releaseModal.form;
      form.resetFields(); // 清理表单数据（可不做）
      this.visibleRelease = true;
      this.releaseMdl = record;
      this.$refs.releaseModal.add(this.releaseMdl);
    },
    // 绑定报表
    handleReport(record) {
      this.$refs.reportModal.add(record);
    },
    handleReleaseOk() {
      this.releaseConfirmLoading = true;
      const form = this.$refs.releaseModal.form;
      form.validateFields((errors, values) => {
        if (!errors) {
          this.$post("/system/menu/formPublishing", values)
            .then((res) => {
              if (res.statusCode === 200) {
                this.$message.success(res.message, 1.5);
                this.visibleRelease = false;
                this.$refs.subList.refresh();
              } else {
                this.$message.error(res.message, 1.5);
              }
            })
            .finally(() => {
              this.releaseConfirmLoading = false;
            });
        } else {
          this.releaseConfirmLoading = false;
        }
      });
    },
    handleReportOk(list) {
      // console.log(list)
    },
    // 版本管理
    versionManage(e) {
      this.visibleVersion = true;
      this.mdlVersion = e.tableName;
      if (this.$refs.versionForm)
        this.$refs.versionForm.refreshList(e.tableName);
    },
    handleCancelVersion() {
      this.visibleVersion = false;
    },
    handleOkVersion() {
      this.confirmLoadingVersion = true;
      this.visibleVersion = false;
      this.$refs.subList.refresh();
      this.confirmLoadingVersion = false;
    },
    handleCopyForm(e) {
      this.$post("/form/formBasicConfigure/copyForm", { uuid: e.uuid }).then(
        (res) => {
          this.$message.success(res.message, 1.5);
          this.$refs.subList.refresh();
        }
      );
    },
    stateChange(value, record) {
      event.stopPropagation();
      let param = {
        uuid: record.uuid,
        status: value,
      };
      this.$post("/form/formBasicConfigure/updateStatusByUuid", param).then(
        (res) => {
          if (res.statusCode === 200) {
            this.$message.success(res.message, 1.5);
            this.$refs.subList.refresh();
          } else {
            this.$message.warn(res.message, 1.5);
          }
        }
      );
    },
    resetSearchForm() {
      this.subQueryParam = {
        puuid: this.masterListKey,
      };
      this.$refs.subList.refresh(true);
    },
    //导入 取消
    importModalCancel() {
      this.importModalVisible = false;
    },
    uploadUrl() {
      return `${baseUrl}${this.url.uploadUrl}`;
    },
    importReportFile() {
      this.$refs.webUploadModal.add();
      this.visibleFile = true;
    },
    exportJSON(record) {
      window.location.href =
        baseUrl +
        "/form/formBasicConfigure/exportFormJson?&uuid=" +
        record.uuid +
        "&token=" +
        Vue.ls.get(ACCESS_TOKEN);
    },
    importReportJson() {
      this.visibleFile = false;
      this.$refs.subList.refresh(true);
    },
    // 调整布局
    handleAdjustLayout(record) {
      this.layoutData = record;
      this.layoutUuid = record.uuid;
      this.layoutVisible = true;
    },
    // 增加布局
    handleAddLayout(params) {
      if (this.layoutData.type === "createPage") {
        this.$refs.designModalLayout.stepList.splice(3, 1);
      }
      this.formType = this.layoutData.type;
      this.$refs.designModalLayout.getData(this.layoutData, params);
      this.visibleDesignLayout = true;
      this.isEdit = true;
      this.layoutVisible = false;
    },
  },
};
</script>

<style scoped>
.page-common-layout .page-common-left + .page-common-content {
  max-width: unset !important;
}
</style>
